package com.gemcoder.system.service;
import static com.gemcoder.system.datasource.JdbcTemplateUtil.executeSQL;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserName;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserId;
import com.gemcoder.system.bo.Result;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllPermissions;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllMenus;
import java.sql.SQLException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import cn.hutool.core.util.StrUtil;

@Service
public class ShutdowntableService {

    public Result getDowntimeData(Map<String,Object> paramMap){
    // 获取参数
    String projectName = paramMap.get("projectName") != null ? String.valueOf(paramMap.get("projectName")) : null;
    String downtimeDuration = paramMap.get("downtimeDuration") != null ? String.valueOf(paramMap.get("downtimeDuration")) : null;
    List<String> timeRange = paramMap.get("timeRange") != null ? (List<String>) paramMap.get("timeRange") : null;
    Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
    Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;

    // 构建查询SQL
    StringBuilder sql = new StringBuilder("SELECT id,project_name, serial_number, project_id, DATE_FORMAT(downtime_start, '%Y-%m-%d %H:%i:%s') AS downtime_start,DATE_FORMAT(downtime_end, '%Y-%m-%d %H:%i:%s') AS downtime_end , downtime_duration, downtime_category, downtime_reason, remarks, reporter, current_status FROM downtime_records WHERE 1=1");
    List<Object> params = new ArrayList<>();

    if (projectName != null && !projectName.isEmpty()) {
        sql.append(" AND project_name like CONCAT('%', ?, '%')");
        params.add(projectName);
    }
    if (downtimeDuration != null && !downtimeDuration.isEmpty()) {
        if ("1小时及以上".equals(downtimeDuration)) {
            sql.append(" AND downtime_duration >= 60");
        } else if ("1小时内".equals(downtimeDuration)) {
            sql.append(" AND downtime_duration < 60");
        }
    }
    if (timeRange != null && !timeRange.isEmpty()) {
        if (timeRange.size() == 2) {
            sql.append(" AND downtime_start >= ? AND downtime_end <= ?");
            params.add(timeRange.get(0));
            params.add(timeRange.get(1));
        }
    }

    // 分页查询
    int offset = (current - 1) * pageSize;
    sql.append(" LIMIT ?, ?");
    params.add(offset);
    params.add(pageSize);

    // 执行查询
    List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());

        // 查询总条数
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) FROM downtime_records dr JOIN project p ON dr.project_id = p.id WHERE 1=1");
        List<Object> countParams = new ArrayList<>();

        if (projectName != null && !projectName.isEmpty()) {
            countSql.append(" AND p.project_name LIKE CONCAT('%', ?, '%')");
            countParams.add(projectName);
        }

        if (downtimeDuration != null && !downtimeDuration.isEmpty()) {
            if ("1小时及以上".equals(downtimeDuration)) {
                countSql.append(" AND dr.downtime_duration >= 60");
            } else if ("1小时内".equals(downtimeDuration)) {
                countSql.append(" AND dr.downtime_duration < 60");
            }
        }

        if (timeRange != null && !timeRange.isEmpty()) {
            if (timeRange.size() == 2) {
                countSql.append(" AND dr.downtime_start >= ? AND dr.downtime_end <= ?");
                countParams.add(timeRange.get(0));
                countParams.add(timeRange.get(1));
            }
        }
        List<Map<String, Object>> countResult = executeSQL(countSql.toString(), countParams.toArray());
    int total = ((Number) countResult.get(0).get("COUNT(*)")).intValue();

    // 返回结果
    Result result = new Result();
    result.setFlag(true);
    result.setMessage("查询成功");
    Map<String, Object> resultData = new HashMap<>();
    resultData.put("total", total);
    resultData.put("data", data);
    result.setData(resultData);
    return result;
}

public Result getCurrentRowData(Map<String,Object> paramMap){
    // 获取参数
    Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
    if (id==null){
        return new Result(false, "id参数错误");
    }
    // 构建查询SQL
    StringBuilder sql = new StringBuilder("SELECT id,project_name, serial_number, project_id, DATE_FORMAT(downtime_start, '%Y-%m-%d %H:%i:%s') AS downtime_start,DATE_FORMAT(downtime_end, '%Y-%m-%d %H:%i:%s') AS downtime_end , downtime_duration, downtime_category, downtime_reason, remarks, reporter, current_status FROM downtime_records WHERE id = ?");
    List<Object> params = new ArrayList<>();
    params.add(id);

    // 执行查询
    List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());

    // 返回结果
    Result result = new Result();
    result.setFlag(true);
    result.setMessage("查询成功");
    result.setData(data.isEmpty() ? null : data.get(0));
    return result;
}

public Result getCurrentUser(Map<String,Object> paramMap){
    // 获取当前登录用户的用户名
    String currentUserName = sdkOfGetCurrentUserName();

    // 返回结果
    Result result = new Result();
    result.setFlag(true);
    result.setMessage("查询成功");
    result.setData(currentUserName);
    return result;
}

    public Result updateDowntimeData(Map<String, Object> paramMap) {
        // 获取参数
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        String downtimeCategory = paramMap.get("downtimeCategory") != null ? String.valueOf(paramMap.get("downtimeCategory")) : null;
        String downtimeReason = paramMap.get("downtimeReason") != null ? String.valueOf(paramMap.get("downtimeReason")) : null;
        String remarks = paramMap.get("remarks") != null ? String.valueOf(paramMap.get("remarks")) : null;

        // 检查 id 是否存在
        if (id == null) {
            return new Result(false, "id 参数错误");
        }

        // 构建更新 SQL
        StringBuilder sql = new StringBuilder("UPDATE downtime_records SET ");
        List<Object> params = new ArrayList<>();

        if (downtimeCategory != null) {
            sql.append("downtime_category = ?, ");
            params.add(downtimeCategory);
        }
        if (downtimeReason != null) {
            sql.append("downtime_reason = ?, ");
            params.add(downtimeReason);
        }
        if (remarks != null) {
            sql.append("remarks = ?, ");
            params.add(remarks);
        }

        // 移除最后的逗号和空格
        if (!params.isEmpty()) {
            sql.setLength(sql.length() - 2);
        } else {
            return new Result(false, "没有要更新的字段");
        }

        sql.append(" WHERE id = ?");
        params.add(id);

        // 执行更新
        int updateCount = executeSQL(sql.toString(), params.toArray());

        // 返回结果
        Result result = new Result();
        if (updateCount > 0) {
            result.setFlag(true);
            result.setMessage("更新成功");
        } else {
            result.setFlag(false);
            result.setMessage("更新失败，记录不存在或没有修改");
        }

        return result;
    }


}